/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eproject.GUI;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Lab
 */
public class connect {
    java.sql.Connection connection;
    java.sql.Statement statement;
    java.sql.ResultSet resultset;
    public static Connection getConnection()
    {
        Connection cn = null;
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
            String url = "jdbc:sqlserver://localhost:1433;databasename=RemedyScheduler";
            String username = "sa";
            String password = "123456";
            cn = DriverManager.getConnection(url,username,password);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
        }
        return cn;
        
    }

    private java.sql.Statement getStatement() throws Exception {
        try {
            if (this.statement == null ? true : this.statement.isClosed()) {
                this.statement = this.getConnection().createStatement();
            }
        } catch (java.sql.SQLException e) {
            throw new Exception("Không tạo được câu lệnh !");
        }
        return this.statement;
    }

    java.sql.ResultSet executeQuery(String query) throws Exception {
        try {
            this.resultset = this.getStatement().executeQuery(query);
        } catch (Exception e) {
            throw e;
        }
        return this.resultset;
    }
    
    private void Close() throws Exception {
        if (this.resultset != null && !this.resultset.isClosed()) {
            this.resultset.close();
            this.resultset = null;

        }
        if (this.statement != null && !this.statement.isClosed()) {
            this.statement.close();
            this.statement = null;
        }
        if (this.connection != null && !this.connection.isClosed()) {
            this.connection.close();
            this.connection = null;
        }
    }
}
